package com.coocaa.x.app.hall.main.ui.category;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.coocaa.x.app.hall.R;
import com.coocaa.x.app.hall.main.ui.category.CategoryName.Category;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.test.action.FocusAction;
import com.coocaa.x.uipackage.generallayout.view.BaseCategoryBar;
import com.coocaa.x.uipackage.utils.CoocaaFresco;
import com.coocaa.x.uipackage.widget.CoocaaDraweeView;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

import java.util.ArrayList;
import java.util.List;


public class CategoryBar extends BaseCategoryBar {
    protected CategoryName mCategoryName = null;
    protected CategoryCursor mCategoryCursor = null;
    protected CoocaaDraweeView iconView = null;
    private int iconWidth = 0;
    private int endX = 0;// JHF
    private int endY = 0;// JHF
    private int page = -1;// JHF
    private String hallUrl = null;
    private boolean isUpload = false;

    public CategoryBar(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public void refreshLayout(String hallUrl) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        mCategoryCursor = new CategoryCursor(mContext);
        mCategoryName = new CategoryName(mContext);
        mCategoryName.setLayoutParams(params);
        mCategoryCursor.setmSkyCategoryName(mCategoryName);

        isUpload = false;
        iconView = null;
        ImageView lineImage = null;
        if (hallUrl != null && !hallUrl.equals("")) {
            this.hallUrl = hallUrl;
            iconView = setImageUrl(hallUrl);
            if (iconView != null) {
                params = new RelativeLayout.LayoutParams(CoocaaApplication.Div(310), CoocaaApplication.Div(80));
                params.setMargins(CoocaaApplication.Div(40), CoocaaApplication.Div(72), CoocaaApplication.Div(40), 0);
                iconView.setLayoutParams(params);
                this.addView(iconView);
                iconWidth = 310;

                lineImage = new ImageView(mContext);
                lineImage.setBackgroundColor(Color.WHITE);
                lineImage.setAlpha((float) 0.3);
                int lineWidth = CoocaaApplication.Div(1);
                if(lineWidth == 0)
                    lineWidth = 1;

                LayoutParams imgLineParams = new LayoutParams(lineWidth, CoocaaApplication.Div(70));
                imgLineParams.addRule(RelativeLayout.RIGHT_OF, iconView.getId());
                imgLineParams.setMargins(CoocaaApplication.Div(iconWidth + 80), CoocaaApplication.Div(77), 0, 0);
                lineImage.setLayoutParams(imgLineParams);
                this.addView(lineImage);
            }
        }

/*      中间文字显示，目前不使用该种方式
        TextView mTitleText = new TextView(mContext);
		mTitleText.setTextSize(CoocaaApplication.Dpi(48));
		mTitleText.setAlpha(0.5f);
		mTitleText.setText(hallName);
		LogUtils.i("xfk0626", "MeasuredWidth:" + mTitleText.getPaint().measureText(hallName));

		params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		params.leftMargin = CoocaaApplication.Div(iconWidth + 30);
		params.topMargin = CoocaaApplication.Div(68);
		if(iconView != null)
			params.addRule(RelativeLayout.RIGHT_OF, iconView.getId());
		mTitleText.setLayoutParams(params);
		this.addView(mTitleText);
*/
//		ImageView lineImage = new ImageView(mContext);
//		lineImage.setBackgroundColor(Color.WHITE);
//		lineImage.setAlpha((float) 0.5);
//		LayoutParams imgLineeParams = new LayoutParams(
//				CoocaaApplication.Div(1), CoocaaApplication.Div(80));
//		imgLineeParams.addRule(RelativeLayout.RIGHT_OF, mTitleText.getId());
//		imgLineeParams.setMargins((int) mTitleText.getPaint().measureText(hallName) + CoocaaApplication.Div(iconWidth + 70), CoocaaApplication.Div(58), 0, 0);
//		lineImage.setLayoutParams(imgLineeParams);
//		this.addView(lineImage);


        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        if (lineImage != null) {
            params.addRule(RelativeLayout.RIGHT_OF, lineImage.getId());
            params.setMargins(CoocaaApplication.Div(iconWidth + 45), 0, 0, 0);
        }

        mCategoryName.setLayoutParams(params);
        mCategoryCursor.setLayoutParams(params);
        this.addView(mCategoryCursor);
        this.addView(mCategoryName);
    }

    public CoocaaDraweeView setImageUrl(String url) {

        //防止loading过程中，按返回键之后Fresco shutdown了，刚好走到这里导致Fresco未初始化而空指针异常。
        try {
            String path = url;

            CoocaaDraweeView mSimpleDraweeView = new CoocaaDraweeView(mContext);
            mSimpleDraweeView
                    .getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.CENTER_INSIDE);
            mSimpleDraweeView
                    .getHierarchy().setPlaceholderImage(R.drawable.bg);
            Uri uri = Uri.parse(path);
            int width = CoocaaApplication.Div(310), height = CoocaaApplication.Div(80);
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                    .setResizeOptions(new ResizeOptions(width, height))
                    .build();
            DraweeController controller = CoocaaFresco.newDraweeControllerBuilder(mContext)
                    .setControllerListener(controllerListener)
                    .setOldController(mSimpleDraweeView.getController())
                    .setImageRequest(request)
                    .build();
            mSimpleDraweeView.setController(controller);

            RoundingParams roundingParams = RoundingParams.fromCornersRadius(10f);
            mSimpleDraweeView.getHierarchy().setRoundingParams(roundingParams);

            return mSimpleDraweeView;
        } catch (NullPointerException e) {
            LogUtils.i("category", "" + e);
        }

        return null;
    }

    ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
        @Override
        public void onSubmit(String s, Object o) {
            isUpload = true;
            LogUtils.i("0730", "sunny facebook onSubmit s:" + s);
        }

        @Override
        public void onFinalImageSet(String s, ImageInfo o, Animatable animatable) {
            LogUtils.i("facebook", "sunny facebook onFinalImageSet s:" + s + ";   o:" + o.toString());
        }

        @Override
        public void onIntermediateImageFailed(String s, Throwable throwable) {
            LogUtils.i("facebook", "sunny facebook onIntermediateImageFailed s:" + s + ";   throwable:" + throwable.toString());
        }

        @Override
        public void onFailure(String s, Throwable throwable) {
            LogUtils.i("facebook", "sunny facebook onFailure s:" + s + ";   throwable:" + throwable.toString());
            if (hallUrl != null && iconView != null)
                iconView.setImageURI(Uri.parse(hallUrl));
        }

        @Override
        public void onRelease(String s) {
            LogUtils.i("facebook", "sunny facebook onRelease s:" + s);
        }
    };

    @Override
    public void addCategoryDatas(BaseCategoryData data) {
        // TODO Auto-generated method stub

        if (mCategoryDatas == null) {
            mCategoryDatas = new ArrayList<BaseCategoryData>();
        }

        mCategoryDatas.add(data);
        mCategoryName.addData(data);
        mCategoryCursor.addData(mCategoryName.getCategoryData());
        updateContentDesc();
    }

    @Override
    public void addCategoryDatas(BaseCategoryData data, int index) {
        // TODO Auto-generated method stub
        if (mCategoryDatas == null) {
            mCategoryDatas = new ArrayList<BaseCategoryData>();
        }

        if (mCategoryDatas.size() > index) {
            mCategoryDatas.add(index, data);
            mCategoryName.addData(data, index);
            mCategoryCursor.addData(mCategoryName.getCategoryData(index), index);
        } else {
            addCategoryDatas(data);
        }
        updateContentDesc();
    }

    @Override
    public void removeCategoryDatas(int index) {
        // TODO Auto-generated method stub
        if (mCategoryDatas.size() > index) {
            mCategoryDatas.remove(index);
            mCategoryName.removeData(index);
            mCategoryCursor.removeData(index);
        }
        updateContentDesc();
    }

    @Override
    public void setCategoryDatas(List<BaseCategoryData> categories) {
        // TODO Auto-generated method stub
        this.mCategoryDatas.addAll(categories);
        mCategoryName.setData(categories);
        mCategoryCursor.setData(mCategoryName.getDataList());
        //mCategoryName.addRedPoint(4, 45);
        if (mCategoryDatas.size() > 0) {
            mCurrentName = mCategoryDatas.get(0).name;
        }
        updateContentDesc();
    }

    @Override
    public void setFocusPos(int pos) {
        // TODO Auto-generated method stub
        if (mCategoryDatas == null
                || mCategoryDatas.size() == 0
                || mCategoryDatas.size() <= pos)
            return;
        if (pos < 0)
            pos = 0;
        else if (pos >= mCategoryDatas.size())
            pos = mCategoryDatas.size() - 1;
        this.mCurrentPos = pos;
        mCategoryName.setFocusPos(pos);
        mCategoryCursor.setFocusPos(pos);
        updateContentDesc();
        if (mCategoryDatas.size() > 0) {
            mCurrentName = mCategoryDatas.get(pos).name;
        }
        updateContentDesc();
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        super.onFocusChange(v, hasFocus);

        if (mCategoryCursor != null) {
            if (hasFocus) {
                mCategoryCursor.setSelected(false);
            } else {
                mCategoryCursor.setSelected(true);
            }
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!mKey) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
                    || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
                    || keyCode == KeyEvent.KEYCODE_DPAD_UP
                    || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
                    || keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                    || keyCode == KeyEvent.KEYCODE_ENTER)
                return true;
            else
                return false;
        }

        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() % 2 == 0) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    if (mCurrentPos > 0) {
                        if (isClickChang)
                            return true;
                        mCurrentPos--;
                        mCategoryName.setFocusPos(mCurrentPos);
                        mCategoryCursor.setFocusPos(mCurrentPos);
                        updateContentDesc();
//					mCategoryName.setMoveX(mCategoryCursor.getMoveX(), mCurrentPos);
                        callbackCategory(keyCode);
                        return true;
                    } else {
                        if (mFocusCallBack != null) {
                            return mFocusCallBack.setPagerFocus(keyCode);
                        }
                    }
                    return true;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    if (mCurrentPos < mCategoryDatas.size() - 1) {
                        if (isClickChang)
                            return true;
                        mCurrentPos++;
//					mCurrentPos = mCategoryCursor.getFocusPos();
//					mCategoryName.setMoveX(mCategoryCursor.getMoveX(), mCurrentPos);
                        mCategoryName.setFocusPos(mCurrentPos);
                        mCategoryCursor.setFocusPos(mCurrentPos);
                        updateContentDesc();
                        callbackCategory(keyCode);
                        return true;
                    } else {
                        if (mFocusCallBack != null) {
                            return mFocusCallBack.setPagerFocus(keyCode);
                        }
                    }
                    return true;
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    if (mCategoryDatas != null && mClickedPos < mCategoryDatas.size() && mClickedPos >= 0)
                        clickCategory(mCategoryDatas.get(mClickedPos), mCurrentPos);
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (mFocusCallBack != null) {
                        return mFocusCallBack.setPagerFocus(KeyEvent.KEYCODE_DPAD_DOWN);
                    }
                    break;
                default:

            }
        }

        return false;
    }

    public void onResume() {
        if (iconView != null && !isUpload && hallUrl != null) {
            LogUtils.i("0731", "category isUpload: " + isUpload);
            try {
                iconView.setImageURI(Uri.parse(hallUrl));
            } catch (Exception e) {
                LogUtils.i("" + e);
            }
        }

        if (this.hallUrl != null && iconView == null) {
            LogUtils.i("0731", "category resume");
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            if (mCategoryCursor == null)
                mCategoryCursor = new CategoryCursor(mContext);
            if (mCategoryName == null)
                mCategoryName = new CategoryName(mContext);
            mCategoryName.setLayoutParams(params);
            mCategoryCursor.setmSkyCategoryName(mCategoryName);
            ImageView lineImage = null;
            iconView = setImageUrl(hallUrl);
            if (iconView != null) {
                this.removeAllViews();
                params = new RelativeLayout.LayoutParams(CoocaaApplication.Div(310), CoocaaApplication.Div(80));
                params.setMargins(CoocaaApplication.Div(40), CoocaaApplication.Div(72), CoocaaApplication.Div(40), 0);
                iconView.setLayoutParams(params);
                this.addView(iconView);
                iconWidth = 310;

                lineImage = new ImageView(mContext);
                lineImage.setBackgroundColor(Color.WHITE);
                lineImage.setAlpha((float) 0.3);
                LayoutParams imgLineParams = new LayoutParams(
                        CoocaaApplication.Div(1), CoocaaApplication.Div(70));
                imgLineParams.addRule(RelativeLayout.RIGHT_OF, iconView.getId());
                imgLineParams.setMargins(CoocaaApplication.Div(iconWidth + 80), CoocaaApplication.Div(77), 0, 0);
                lineImage.setLayoutParams(imgLineParams);
                this.addView(lineImage);

                if (mCategoryName != null && mCategoryCursor != null) {
                    params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                    if (lineImage != null) {
                        params.addRule(RelativeLayout.RIGHT_OF, lineImage.getId());
                        params.setMargins(CoocaaApplication.Div(iconWidth + 45), 0, 0, 0);
                    }
                    mCategoryName.setLayoutParams(params);
                    mCategoryCursor.setLayoutParams(params);
                    this.addView(mCategoryCursor);
                    this.addView(mCategoryName);
                }
            }
        }
    }

    @Override
    public void onDestory() {
        // TODO Auto-generated method stub
        mCategoryChangeListener = null;
        mCategoryClickListener = null;

        if (mCategoryCursor != null) {
            mCategoryCursor.onDestory();
        }

        if (mCategoryName != null) {
            mCategoryName.destory();
        }

        if (mCategoryDatas != null)
            mCategoryDatas.clear();

        this.removeAllViews();
        this.destroyDrawingCache();
    }

    @Override
    // 2012.11.8 JHF
    public boolean onTouchEvent(MotionEvent event) {
        int what = event.getAction();

        switch (what) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                endX = (int) event.getRawX();
                endY = (int) event.getRawY();
                int onPage = -1;
                onPage = getCategoryPage(endX, endY);
                if (onPage != page && onPage != -1) {
                    if (onPage > page) {

                    }
                    if (onPage < page) {
                    }

                }
                break;
            case MotionEvent.ACTION_MOVE:

                break;
            default:
                break;
        }
        return true;
    }

    // 2012.11.8 JHF
    public int getCategoryPage(int posX, int posY) {

        List<Category> cateList = new ArrayList<Category>();
        if (mCategoryName != null) {// 当服务器未给予分类信息时，鼠标点击无效
            cateList = mCategoryName.getDataList();
        }
        int mpage = -1;
        if (cateList != null) {// 从服务器取得的数据不为空时执行
            for (int i = 0; i < cateList.size(); i++) {
                if (posX > cateList.get(i).mX
                        && posX < (cateList.get(i).mX + cateList.get(i).mWidth)) {
                    mpage = i;
                    return mpage;

                }
            }
        }
        return mpage;
    }

    private void updateContentDesc() {
        FocusAction action = new FocusAction(mCategoryDatas.size(), mCurrentPos);
        setContentDescription(action.toJSONString());
    }
//	// 2012.11.9 JHF
//	OnHoverListener gvHoverListener = new OnHoverListener() {
//		@Override
//		public boolean onHover(View v, MotionEvent event) {
//			int what = event.getAction();
//			switch (what) {
//			case MotionEvent.ACTION_HOVER_ENTER: // 鼠标进入view
//				break;
//			case MotionEvent.ACTION_HOVER_MOVE: // 鼠标在view上
//				break;
//			case MotionEvent.ACTION_HOVER_EXIT: // 鼠标离开view
//				break;
//			case MotionEvent.ACTION_DOWN:
//				break;
//			}
//			return false;
//		}
//	};
}
